package com.dms.modules.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.community.dto.CommunityPostDetailDTO;
import com.dms.modules.community.dto.CommunitySearchDTO;
import com.dms.modules.community.entity.CommunityCategory;
import com.dms.modules.community.entity.CommunityFavorite;
import com.dms.modules.community.entity.CommunityLike;
import com.dms.modules.community.entity.CommunityPost;
import com.dms.modules.community.entity.CommunitySearchHistory;
import com.dms.modules.community.mapper.CommunityCategoryMapper;
import com.dms.modules.community.mapper.CommunityFavoriteMapper;
import com.dms.modules.community.mapper.CommunityLikeMapper;
import com.dms.modules.community.mapper.CommunityPostMapper;
import com.dms.modules.community.mapper.CommunitySearchHistoryMapper;
import com.dms.modules.community.service.CommunitySearchService;
import com.dms.modules.user.service.UserCenterService;
import com.dms.modules.user.vo.UserInfoVO;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunitySearchServiceImpl extends ServiceImpl<CommunitySearchHistoryMapper, CommunitySearchHistory> implements CommunitySearchService {

    private final Gson gson = new Gson();

    @Autowired
    private CommunityCategoryMapper categoryMapper;

    @Autowired
    private CommunityPostMapper postMapper;

    @Autowired
    private CommunityLikeMapper likeMapper;

    @Autowired
    private CommunityFavoriteMapper favoriteMapper;

    @Autowired
    private UserCenterService userCenterService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordSearch(Long userId, String keyword, Long categoryId) {
        try {
            // 查找是否存在相同用户和关键词的记录
            LambdaQueryWrapper<CommunitySearchHistory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunitySearchHistory::getUserId, userId)
                   .eq(CommunitySearchHistory::getKeyword, keyword);
            
            CommunitySearchHistory history = getOne(wrapper);
            
            if (history != null) {
                // 更新搜索次数和最后搜索时间
                LambdaUpdateWrapper<CommunitySearchHistory> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(CommunitySearchHistory::getId, history.getId())
                           .set(CommunitySearchHistory::getSearchCount, history.getSearchCount() + 1)
                           .set(CommunitySearchHistory::getLastSearchTime, LocalDateTime.now())
                           .set(CommunitySearchHistory::getCategoryId, categoryId);
                update(updateWrapper);
            } else {
                // 创建新记录
                history = new CommunitySearchHistory();
                history.setUserId(userId);
                history.setKeyword(keyword);
                history.setCategoryId(categoryId);
                history.setSearchCount(1);
                history.setLastSearchTime(LocalDateTime.now());
                save(history);
            }
            
            log.info("记录搜索历史成功: userId={}, keyword={}, categoryId={}", userId, keyword, categoryId);
        } catch (Exception e) {
            log.error("记录搜索历史失败: userId={}, keyword={}, error={}", userId, keyword, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<CommunitySearchDTO> getUserRecentSearches(Long userId, Integer limit) {
        try {
            // 获取用户最近搜索记录
            List<CommunitySearchHistory> histories = baseMapper.getUserRecentSearches(userId, limit);
            
            // 获取涉及的分类ID
            List<Long> categoryIds = histories.stream()
                    .map(CommunitySearchHistory::getCategoryId)
                    .filter(id -> id != null)
                    .distinct()
                    .collect(Collectors.toList());
            
            // 查询分类信息
            Map<Long, String> categoryMap = categoryMapper.selectBatchIds(categoryIds)
                    .stream()
                    .collect(Collectors.toMap(CommunityCategory::getId, CommunityCategory::getName));
            
            // 转换为DTO
            return histories.stream().map(history -> {
                CommunitySearchDTO dto = new CommunitySearchDTO();
                BeanUtils.copyProperties(history, dto);
                if (history.getCategoryId() != null) {
                    dto.setCategoryName(categoryMap.get(history.getCategoryId()));
                }
                return dto;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取用户搜索历史失败: userId={}, error={}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<CommunitySearchDTO> getHotKeywords(Integer limit) {
        try {
            // 获取热门搜索词
            List<CommunitySearchHistory> histories = baseMapper.getHotKeywords(limit);
            
            // 转换为DTO
            return histories.stream().map(history -> {
                CommunitySearchDTO dto = new CommunitySearchDTO();
                BeanUtils.copyProperties(history, dto);
                return dto;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取热门搜索词失败: error={}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearUserSearchHistory(Long userId) {
        try {
            LambdaUpdateWrapper<CommunitySearchHistory> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(CommunitySearchHistory::getUserId, userId);
            return remove(wrapper);
        } catch (Exception e) {
            log.error("清空用户搜索历史失败: userId={}, error={}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public IPage<CommunityPostDetailDTO> searchPosts(Long currentUserId, String keyword, Page<CommunityPostDetailDTO> page) {
        try {
            log.debug("搜索帖子: currentUserId={}, keyword={}, pageNum={}, pageSize={}", 
                currentUserId, keyword, page.getCurrent(), page.getSize());

            // 构建搜索条件
            LambdaQueryWrapper<CommunityPost> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPost::getDeleted, 0)  // 未删除的帖子
                  .and(w -> w
                      .like(CommunityPost::getTitle, keyword)
                      .or()
                      .like(CommunityPost::getContent, keyword))
                  .orderByDesc(CommunityPost::getCreateTime);  // 按创建时间倒序排序

            // 执行分页查询
            IPage<CommunityPost> postPage = postMapper.selectPage(new Page<>(page.getCurrent(), page.getSize()), wrapper);

            // 转换为DetailDTO并设置额外信息
            List<CommunityPostDetailDTO> records = postPage.getRecords().stream()
                .map(post -> {
                    CommunityPostDetailDTO detailDTO = new CommunityPostDetailDTO();
                    BeanUtils.copyProperties(post, detailDTO);

                    // 设置图片列表
                    if (post.getImages() != null) {
                        try {
                            detailDTO.setImages(gson.fromJson(post.getImages(), ArrayList.class));
                        } catch (Exception e) {
                            log.warn("解析图片列表失败: postId={}, images={}", post.getId(), post.getImages());
                            detailDTO.setImages(new ArrayList<>());
                        }
                    }

                    // 设置用户信息
                    try {
                        UserInfoVO userInfo = userCenterService.getUserInfo(post.getUserId());
                        if (userInfo != null) {
                            detailDTO.setUserNickname(userInfo.getNickname());
                            detailDTO.setUserAvatar(userInfo.getAvatar());
                        }
                    } catch (Exception e) {
                        log.warn("获取用户信息失败: userId={}, error={}", post.getUserId(), e.getMessage());
                        detailDTO.setUserNickname("用户" + post.getUserId());
                        detailDTO.setUserAvatar("/static/images/default-avatar.jpg");
                    }

                    // 设置当前用户是否点赞和收藏
                    if (currentUserId != null) {
                        try {
                            // 查询点赞状态
                            LambdaQueryWrapper<CommunityLike> likeWrapper = new LambdaQueryWrapper<>();
                            likeWrapper.eq(CommunityLike::getUserId, currentUserId)
                                     .eq(CommunityLike::getTargetId, post.getId())
                                     .eq(CommunityLike::getTargetType, 1);
                            detailDTO.setIsLiked(likeMapper.selectCount(likeWrapper) > 0);

                            // 查询收藏状态
                            LambdaQueryWrapper<CommunityFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
                            favoriteWrapper.eq(CommunityFavorite::getUserId, currentUserId)
                                         .eq(CommunityFavorite::getPostId, post.getId());
                            detailDTO.setIsFavorited(favoriteMapper.selectCount(favoriteWrapper) > 0);
                        } catch (Exception e) {
                            log.warn("获取用户交互状态失败: userId={}, postId={}, error={}", 
                                   currentUserId, post.getId(), e.getMessage());
                            detailDTO.setIsLiked(false);
                            detailDTO.setIsFavorited(false);
                        }
                    } else {
                        detailDTO.setIsLiked(false);
                        detailDTO.setIsFavorited(false);
                    }

                    return detailDTO;
                })
                .collect(Collectors.toList());

            // 构建返回结果
            IPage<CommunityPostDetailDTO> result = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
            result.setRecords(records);

            log.debug("搜索帖子完成: keyword={}, total={}", keyword, result.getTotal());
            return result;
        } catch (Exception e) {
            log.error("搜索帖子失败: keyword={}, error={}", keyword, e.getMessage(), e);
            throw e;
        }
    }
} 